from fastapi import APIRouter, Depends, HTTPException
from typing import List, Optional
from pydantic import BaseModel
from datetime import datetime
from sqlalchemy.orm import Session
from ..database import get_db
from ..data_clean.models import BrandConfig
import logging

logger = logging.getLogger(__name__)

router = APIRouter(
    tags=["brand"],
    responses={404: {"description": "Not found"}},
)

# 品牌基础模型
class BrandBase(BaseModel):
    name: str
    category: Optional[str] = None
    is_active: Optional[bool] = None

# 创建品牌模型
class BrandCreate(BrandBase):
    pass

# 更新品牌模型
class BrandUpdate(BaseModel):
    name: Optional[str] = None
    category: Optional[str] = None
    is_active: Optional[bool] = None

# 品牌响应模型
class BrandResponse(BrandBase):
    id: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True

"""
获取所有品牌列表
---
返回:
- 200: 返回所有品牌列表
"""
@router.get("/", response_model=List[BrandResponse])
async def get_brands(
    db: Session = Depends(get_db)
):
    brands = db.query(BrandConfig).all()
    return brands

"""
创建新品牌
---
参数:
- brand: 品牌创建模型
- db: 数据库会话

返回:
- 201: 创建成功，返回品牌详情
- 400: 创建失败，品牌名称已存在
"""
@router.post("/", response_model=BrandResponse, status_code=201)
async def create_brand(
    brand: BrandCreate,
    db: Session = Depends(get_db)
):
    try:
        logger.info(f"Received brand creation request: {brand.dict()}")
        # 检查品牌名称是否已存在
        existing_brand = db.query(BrandConfig).filter(BrandConfig.name == brand.name).first()
        if existing_brand:
            raise HTTPException(status_code=400, detail="品牌名称已存在")
        
        db_brand = BrandConfig(**brand.dict())
        db.add(db_brand)
        try:
            db.commit()
            db.refresh(db_brand)
            logger.info(f"Successfully created brand: {db_brand.id}")
            return db_brand
        except Exception as e:
            db.rollback()
            logger.error(f"Database error while creating brand: {str(e)}")
            raise HTTPException(status_code=400, detail=f"品牌创建失败: {str(e)}")
    except Exception as e:
        logger.error(f"Error in create_brand: {str(e)}")
        raise

"""
更新品牌信息
---
参数:
- brand_id: 品牌ID
- brand: 更新的品牌信息
- db: 数据库会话

返回:
- 200: 更新成功，返回更新后的品牌信息
- 404: 品牌不存在
- 400: 更新失败，品牌名称已存在
"""
@router.put("/{brand_id}", response_model=BrandResponse)
async def update_brand(
    brand_id: int,
    brand: BrandUpdate,
    db: Session = Depends(get_db)
):
    db_brand = db.query(BrandConfig).filter(BrandConfig.id == brand_id).first()
    if not db_brand:
        raise HTTPException(status_code=404, detail="品牌不存在")
    
    # 如果更新名称，检查新名称是否已存在
    if brand.name and brand.name != db_brand.name:
        existing = db.query(BrandConfig).filter(BrandConfig.name == brand.name).first()
        if existing:
            raise HTTPException(status_code=400, detail="品牌名称已存在")
    
    # 更新字段
    update_data = brand.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_brand, key, value)
    
    try:
        db.commit()
        db.refresh(db_brand)
        return db_brand
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"品牌更新失败: {str(e)}")

"""
删除品牌
---
参数:
- brand_id: 品牌ID
- db: 数据库会话

返回:
- 200: 删除成功
- 404: 品牌不存在
"""
@router.delete("/{brand_id}")
async def delete_brand(
    brand_id: int,
    db: Session = Depends(get_db)
):
    db_brand = db.query(BrandConfig).filter(BrandConfig.id == brand_id).first()
    if not db_brand:
        raise HTTPException(status_code=404, detail="品牌不存在")
    
    try:
        db.delete(db_brand)
        db.commit()
        return {"message": "品牌删除成功"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"品牌删除失败: {str(e)}") 